<?php 
class system_date {
	private $_offset = 0;
	private $_timezone = 'UTC';
	private $_time = 0;
	
	public function __construct($time=null, $zone=null) {
		date_default_timezone_set($this->_timezone);
		if($time===null) {
			$this->_time = time();
		} else {
			if(is_numeric($time)) {
				$this->_time = $time;
			} else {
				$this->_time = strtotime($time);
			}
		}
		$this->setTimezone($zone);
	}
	
	/**
	 * @return system_date
	 */
	public function setTimezone($zone=null) {
		$oldzone = @date_default_timezone_get();
		if($zone === null) {
			$zone = $oldzone;
		}
		if(function_exists('timezone_open')) {
			if(!@timezone_open($zone)) {
				throw new system_exception("timezone ($zone) is not a known timezone");
			}
		}
		$result = @date_default_timezone_set($zone);
        if ($result === true) {
            $this->_offset   = mktime(0, 0, 0, 1, 2, 1970) - gmmktime(0, 0, 0, 1, 2, 1970);
            $this->_timezone = $zone;
            $this->_time -= $this->_offset;
        }
		date_default_timezone_set($oldzone);		
		return $this;
	}
	
	public function getTimezone() {
		return $this->_timezone;
	}
	
	public function get() {
		return $this->_time;
	}
	
	public function toString($format=null) {
		if($format===null) {
			return date('M d, Y, H:i:s A', $this->_time);
		} else {
			return date($format, $this->_time);
		}
	}
	
	public function __toString() {
		return $this->toString(null);
	}
	
	public static function timestamp($time=null, $zone=null) {
		$self = new self($time, $zone);
		return $self->get();
	}
	
}
